import { loginApi, logoutApi } from '@/http/api'

// 上次启动时的用户信息
let userInfoHistory = uni.getStorageSync('userInfo') || {};
let tokenHistory = uni.getStorageSync('toekn') || '';
let state = {
		//是否已经登录
		hasLogin: Boolean(Object.keys(userInfoHistory).length),
		//用户信息
		info: userInfoHistory,
		token: tokenHistory
	},
	getters = {
		info(state) {
			return state.info;
		},
		hasLogin(state){
			return state.hasLogin;
		}
	},
	mutations = {
		logout(state) {
			state.info = {};
			state.hasLogin = false;
			uni.setStorageSync('userInfo', {});
			uni.removeStorageSync('token');
		},
		SET_USERINFO: (state, res) => {
			//原有的结合传来的参数
			let _info = state.info;
			state.info = Object.assign({}, _info, res.user);
			//设置为已经登录
			state.token = res.token;
			state.hasLogin = true;
			console.log('state.info',state.info);
			//存储最新的用户数据到本地持久化存储
			uni.setStorageSync('userInfo', state.info);
			uni.setStorageSync('token', state.token)
		},
    helpHit(state) {
      state.info.isFirst = 0;
    }
	},
	actions = {
		// 登录
		Login({ commit }, param) {
			return new Promise((resolve, reject) => {
				loginApi(param).then(res => {
					if (res.code === 200) {
						commit('SET_USERINFO', res)
						resolve()
					}else{
						reject(res)
					}
				}).catch(err => {
					reject(err)
				})
			})
		},
		Logout({ commit }){
			// uni.showLoading({mask:true});
			logoutApi().then(res => {
				if (res.code === 200) {
					commit('logout');
					// uni.hideLoading();
				}
			})
		}
	}
export default {
	namespaced: true,
	state,
	getters,
	mutations,
	actions
}